﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Twilight.TwitterData;
using System.Windows.Media.Imaging;
using System.ComponentModel;
using System.Windows.Threading;

namespace Twilight.ViewModels
{
    public abstract class BaseViewModel : INotifyPropertyChanged
    {
        protected BaseDataProvider dataProvider;
        protected bool loaded = false;

        public string Username { get; protected set; }
        public string Followers { get; protected set; }
        public BitmapImage Avatar { get; protected set; }
        public Uri FollowUri { get; protected set; }

        public BaseViewModel()
        {
            LoadData();
        }

        public static Control RootVisual { get; set; }

        protected virtual void LoadData()
        {
            if (IsDesignTime())
            {
                loaded = true;
                Username = "bryantlikes";
                Followers = "100,000 following";
                Avatar = new BitmapImage(new Uri("http://static.twitter.com/images/default_profile_normal.png"));
            }
            else
            {
                if (RootVisual == null)
                {
                    try { RootVisual = Application.Current.RootVisual as Control; }
                    catch { };
                }
                dataProvider = BaseDataProvider.Instance;
                Username = dataProvider.Username;
                FollowUri = new Uri("http://twitter.com/" + Username);
                dataProvider.TweetsUpdated += new EventHandler<TweetsUpdatedEventArgs>(DataProvider_TweetsUpdated);
            }
        }

        protected virtual void DataProvider_TweetsUpdated(object sender, TweetsUpdatedEventArgs e)
        {
            if (RootVisual.Dispatcher.CheckAccess())
            {
                UpdateTweets(e.Tweets);
            }
            else
            {
                RootVisual.Dispatcher.BeginInvoke(() => UpdateTweets(e.Tweets));
            }
        }

        protected abstract void UpdateTweets(Tweet[] tweets);

        protected void LoadAvatar(Uri source)
        {
            Avatar = new BitmapImage(source); 
            PropertyUpdated("Avatar");
        }

        protected bool IsDesignTime()
        {
            return Twilight.Utilities.DesignerProperties.GetIsInDesignMode(Application.Current.RootVisual);
        }

        protected void PropertyUpdated(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}
